package com.wit.paper.dao;

import com.wit.paper.model.UserPo;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

/**
 * Created by 何鹏帅 on 2016/11/5.
 */
@SuppressWarnings("all")
public class UserDao extends JdbcDaoSupport{
    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Collection<UserPo> doquery() {
        String sql = "SELECT * FROM userinfo";
        return super.getJdbcTemplate().query(sql, new RowMapper() {
            @Override
            public Object mapRow(ResultSet rs, int rowNum) {
                UserPo user = new UserPo();
                try {
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setId(rs.getInt("id"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return user;
            }
        });
    }

    public void insert(UserPo userPo) {
        String sql = "insert into userinfo(username, password) " + "value(" + userPo.toString() + ")";
        try {
            super.getJdbcTemplate().update(sql);
        } catch (DuplicateKeyException e) {
            msg = "帐号存在";
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
